<?php 
/**
*
* Kreditor Order Confirmation Handler
*
* @version $Id: checkout.kreditor.php 
* @package VirtueMart
* @subpackage html
* @copyright Copyright (C) 2007  All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details.
*
* http://virtuemart.net
*/
$logging=false;
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );   



$byt = array ( "Ã…", "Ã„", "Ã–", "Ã¥", "Ã¤", "Ã¶" );

$med = array ( "Å", "Ä", "Ö", "å", "ä", "ö" );

$byt2 = array ( "Å", "Ä", "Ö", "&aring;", "&auml;", "&ouml;" );

//$text = str_replace($med,$byt,$text); 

//define (PAYS_NOTEMONEYREC,'Observera att Payson AB kommer att st&aring; som betalningsmottagare p&aring; ditt kontoutdrag.');
//define (PAYS_SUCCESSFUL_PAYMENT_COMMENT,'Din betalning har godk&auml;nts av Payson med referensnummer: ');

//define (PAYS_NOTEMONEYREC,'Observera att Payson AB kommer att stå som betalningsmottagare på ditt kontoutdrag.');

define('ABSLPATH1', dirname(__FILE__).'/');
$shorten_path1 = substr(ABSLPATH1, 0, -1);
$shorten_path1 .= "/ps_kreditor_language.php";
//echo $shorten_path . "<br />";
if(file_exists($shorten_path1))
{
	include_once($shorten_path1);
	activateLanguage();
}
else
{
	define('ABSLPATH2', dirname(__FILE__).'/');
	$shorten_path2 = substr(ABSLPATH2, 0, -5);
	$shorten_path2 .= "/classes/payment/ps_kreditor_language.php";	
	//echo $shorten_path . "<br />";
	
	if(file_exists($shorten_path2))
	{
		include_once($shorten_path2);
		activateLanguage();
	}
	else
	{
		echo "REPORT THESE lines to Kreditor/Klarna technical support!<br />";
		echo "These include error where tried for kreditor_language - kreditor.php!<br />";
		echo $shorten_path1 . "<br />" . $shorten_path2 . "<br />";
	}
}

$langInfo = new Singleton("language");

define (KREDITOR_SUCCESSFUL_PAYMENT_COMMENT, $langInfo->TEXT_SUCCESSFUL_PAYMENT_COMMENT);
define (KREDITOR_CANCEL_REASON_START, $langInfo->TEXT_CANCEL_REASON);
define (KREDITOR_LOCAL_CANCEL, $langInfo->TEXT_PURCHASE_CANCELLED_BASKET_SAVED);

/**
* Read the post from payson
* I have used $_REQUEST instead of $_POST, because
* the "direct return" feature comes here using the GET method
* and $_REQUEST includes $_POST as well as $_GET
**/
if( !isset( $_GET["order_number"] ) || empty( $_GET["order_number"] ))
  echo "Order ID is not set or emtpy!";
else {
  
  /* Load the Kreditor Configuration File */ 
  require_once( CLASSPATH. 'payment/ps_kreditor.cfg.php' );
  //require_once( CLASSPATH. 'kreditor.php' );
  
  /* collect some variables */
  
  $order_number   = $_GET["order_number"];
  $faktura_number = $_SESSION['faktura_number'];
  

  ////////////////////////////////////////////////////////////////////////
  function stringDump($string){
  $filename= "./kreditor_checkout_log";
  $handle = fopen($filename, "a");
  fwrite($handle, "** ".date("Y-m-d H:i:s")." **\n");
  fwrite($handle, "Data: $string; \n");
  fclose($handle);
}
 if ($logging){
  $kd_ip           = $_SERVER["REMOTE_ADDR"];
  stringDump("\n\nMessage from:   ".$kd_ip);
  stringDump("  OkURL:            ".$okurl);
  stringDump("  PaysonRef:        ".$paysonref);
  stringDump("  Received MD5:     ".$compare_hash2);
  stringDump("  Calulated MD5:    ".$compare_hash1);
  stringDump("  Fee:              ".$fee);
  stringDump("  ------------------------------------------- ");
  }
  
  ///////////////////////////////////////////////////////////////////////
  $imageurl = VM_THEMEURL . 'images/';
 	    
        $qv = "SELECT trans_order_id, temp_data FROM #__{vm}_paytrans ";
        $qv .= "WHERE trans_order_id='".$order_number."'";
        $dbbt = new ps_DB;
        $dbbt->query($qv);
        $dbbt->next_record();
        $d_commasep  = $dbbt->f("temp_data");
        //fixa d igen
        $d_rows = split("[;]" , $d_commasep);
        //print_r($d_rows);exit();
        for ($j=0; $j<sizeof($d_rows); $j++ ){
          $d_onerow = split("[,]" , $d_rows[$j]);
          
          $key   = (string)$d_onerow[0];
          $value = (string)$d_onerow[1];
          
          $key=str_replace(',','',$key);
          $key=str_replace(' ','',$key);
          $key = rtrim($key);
          $key = ltrim($key);
          
          $value=str_replace(';','',$value);
          $value=str_replace('\r','',$value);
          $value=str_replace('\n','',$value);
          if ($key != ""){
            $d["$key"] = $value;
          }
        }   
        $order_total = $dbbt->f("amount");
        // hämta resultat databas
         $q2  = "SELECT pay_result FROM #__{vm}_paytrans WHERE trans_order_id = '".$order_number."' AND trnumber = '".$faktura_number."'";
				
				  
	      $dbst = new ps_DB;
	      $dbst->setQuery($q2);
	      $dbst->query();
	      
	      
        if  ( $dbst->f('pay_result') == "APPROVED")  {
            
            //make correct URL to invoice at Kreditor:
            //$invoice_url = str_replace("NO",$faktura_number,$KREDITOR_PDF_INVOICE);
            
            
            // UPDATE THE ORDER STATUS to 'VALID'
            $d['order_status'] = KREDITOR_VERIFIED_STATUS;
             // Setting this to "Y" = yes is required by Danish Law for wexample
            $d['notify_customer'] = "N";
            $d['include_comment'] = "Y";
            // Notifying the customer about the transaction nr and authcode
            // the order Status Update
            $d['order_comment'] = KREDITOR_SUCCESSFUL_PAYMENT_COMMENT . $faktura_number ;
            //$d['order_comment'] .= "\n Länk till faktura: ". $invoice_url;
           // $d['order_comment'] =  str_replace($med,$byt,$d['order_comment']);
            //$d['customer_note'] .= '<br />-----------------------------------<br />' . $d['order_comment'];
            
            //---------------- fix and trix-------------------------------
            $_REQUEST['ship_to_info_id'] = $d['ship_to_info_id'];
            
            require_once ( CLASSPATH . 'ps_checkout.php' );
            $ps_checkout = new ps_checkout();
            // Create a Shipping Object and assign it to the _SHIPPING attribute
		    // We take the first Part of the Shipping Rate Id String
		    // which holds the Class Name of the Shipping Module
		    
			$rate_array = explode( "|",urldecode($d['shipping_rate_id']) );
		    
		    $filename = basename( $rate_array[0] );
		    if ($filename != ""){
		      include_once( CLASSPATH. "shipping/".$filename.".php" );
		      eval( "\$ps_checkout->_SHIPPING =& new ".$filename."();");
		    }
		    $_REQUEST['shipping_rate_id'] = $d['shipping_rate_id'];
		    
            $ps_checkout->add($d); 
            // -------------- get orderid and update paytrans ------------------
            $q = "SELECT order_id,user_info_id FROM #__{vm}_orders WHERE order_number ='".$order_number."'";
            if ($logging){
              stringDump($q);
            }
		    $db = new ps_DB;
		    $db->query($q);
		    $db->next_record();
		    $order_id = $db->f("order_id");
		    $user_info_id = $db->f("user_info_id");
		    //--------------------- now update paytrans------------------------
		    $q2  = "UPDATE  #__{vm}_paytrans SET orders_id='".$order_id."' WHERE trans_order_id='".$order_number."' ";	  
		    if ($logging){
              stringDump($q2);
            }
	        //$dbst = new ps_DB;
	        $dbst->setQuery($q2);
	        $dbst->query();    
			//------------------------ update Kreditor invoice--------------------------------
			require_once(CLASSPATH ."payment/ps_kreditor.cfg.php");
			require_once(CLASSPATH ."kreditor.php");
	
			update_orderno(KREDITOR_EID, $faktura_number, KREDITOR_SECRET, $order_id, $result);
            //---------------------klart, plocka ut kundens angivna mailadr--------------------
            $q3 = "SELECT user_email FROM #__{vm}_user_info WHERE user_info_id = '".$user_info_id."'";
            if ($logging){
              stringDump($q3);
            }
		    $db3 = new ps_DB;
		    $db3->query($q3);
		    $db3->next_record();
		    $ch_email = $db3->f("user_email");
		    
		    
    ?> 
            
			<h3><img src="<?php echo $imageurl ?>button_ok.png" align="center" alt="Success" border="0" />
			<?php echo $VM_LANG->_('PHPSHOP_THANKYOU') ?></h3>
            
            <h2><?php echo $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS') ?></h2>
            <p><?php echo KREDITOR_SUCCESSFUL_PAYMENT_COMMENT . $faktura_number ;?></p>
			
			
			<?php echo $VM_LANG->_('PHPSHOP_EMAIL_SENDTO') .": <strong>". $ch_email; ?></strong><br />
            <br />
			<p><a href="<?php @$sess->purl( SECUREURL."index.php?option=com_virtuemart&page=account.order_details&order_id=".$order_id ) ?>">
			   <?php echo $VM_LANG->_('PHPSHOP_ORDER_LINK') ?></a>
			</p>
        <?php
        
        }
        else {
            // the Payment wasn't successful. Maybe the Payment couldn't
            // be verified and is pending
            // UPDATE THE ORDER STATUS to 'INVALID'
            $d['order_status'] = KREDITOR_INVALID_STATUS; 
            $kreditor_answer = $faktura_number;
            
    ?> 
            <img src="<?php echo $imageurl ?>button_cancel.png" align="center" alt="Cancel" border="0" />
            <h2><?php echo KREDITOR_LOCAL_CANCEL ?></h2>
            <p><?php echo $kreditor_answer; ?></p>
            <p><?php echo $_SESSION['currency_error']; ?></p>
        <?php
        } 
  
  
}
?> 

